package xyz.thoughtset.viewer.common.ai.model.service;

import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import xyz.thoughtset.viewer.common.ai.model.dao.ModelParamDao;
import xyz.thoughtset.viewer.common.ai.model.entity.ModelParam;
import xyz.thoughtset.viewer.common.ai.model.entity.ModelParam;
import xyz.thoughtset.viewer.common.ai.model.entity.purpose.BaseModelSetting;
import xyz.thoughtset.viewer.common.crud.core.service.BaseServiceImpl;

import java.util.Map;

@Service
public class ModelParamServiceImpl extends BaseServiceImpl<ModelParamDao, ModelParam> implements ModelParamService {
    @SneakyThrows
    @Override
    public ModelParam saveData(ModelParam data) {
        if (!ObjectUtils.isEmpty(data.getModelArgs())){
            data.setSetting(mapper.writeValueAsString(data.getModelArgs()));
        }
        if (!ObjectUtils.isEmpty(data.getParamMap())){
            data.setParamJson(mapper.writeValueAsString(data.getParamMap()));
        }
        return super.saveData(data);
    }

    @Override
    @SneakyThrows
    public ModelParam selectDetail(String pkey) {
        ModelParam data = super.selectDetail(pkey);
        if (StringUtils.hasText(data.getParamJson())){
            data.setParamMap(mapper.readValue(data.getParamJson(), Map.class));
        }
        if (StringUtils.hasText(data.getSetting())){
            data.setModelArgs((BaseModelSetting) mapper.readValue(data.getSetting(), data.getPurpose().getSettingClass()));
        }
        return data;
    }
}
